// Synchronization (同步) 示例
program SynchronizationExample;

{$mode objfpc}{$H+}

uses
  Classes, SysUtils, SyncObjs;

type
  // 共享数据结构
  TSharedData = class
  public
    Value: Integer;
    CriticalSection: TCriticalSection;
    
    constructor Create;
    destructor Destroy; override;
  end;

constructor TSharedData.Create;
begin
  inherited Create;
  Value := 0;
  CriticalSection := TCriticalSection.Create;
end;

destructor TSharedData.Destroy;
begin
  CriticalSection.Free;
  inherited Destroy;
end;

// 线程类，用于演示同步
TWorkerThread = class(TThread)
private
  FSharedData: TSharedData;
  FThreadID: Integer;
protected
  procedure Execute; override;
public
  constructor Create(ASharedData: TSharedData; AThreadID: Integer);
end;

constructor TWorkerThread.Create(ASharedData: TSharedData; AThreadID: Integer);
begin
  inherited Create(False);
  FSharedData := ASharedData;
  FThreadID := AThreadID;
  FreeOnTerminate := True;
end;

procedure TWorkerThread.Execute;
var
  I: Integer;
begin
  for I := 1 to 3 do
  begin
    if Terminated then
      Exit;
      
    // 使用临界区保护共享数据
    FSharedData.CriticalSection.Enter;
    try
      WriteLn('线程 ', FThreadID, ' 访问共享数据，原值: ', FSharedData.Value);
      Sleep(100); // 模拟处理时间
      Inc(FSharedData.Value);
      WriteLn('线程 ', FThreadID, ' 修改后值: ', FSharedData.Value);
    finally
      FSharedData.CriticalSection.Leave;
    end;
    
    Sleep(500); // 线程间间隔
  end;
  
  WriteLn('线程 ', FThreadID, ' 执行完毕');
end;

var
  SharedData: TSharedData;
  Thread1, Thread2: TWorkerThread;

begin
  WriteLn('=== Pascal 同步机制示例 ===');
  WriteLn;
  
  // 创建共享数据
  SharedData := TSharedData.Create;
  
  try
    // 创建并启动线程
    WriteLn('创建并启动线程...');
    Thread1 := TWorkerThread.Create(SharedData, 1);
    Thread2 := TWorkerThread.Create(SharedData, 2);
    
    // 等待线程完成
    WriteLn('等待线程完成...');
    Thread1.WaitFor;
    Thread2.WaitFor;
    
    WriteLn;
    WriteLn('最终共享数据值: ', SharedData.Value);
  finally
    SharedData.Free;
  end;
  
  WriteLn;
  WriteLn('同步示例完成。');
  ReadLn;
end.